// 评论相关业务逻辑

// 引入数据库执行的工具函数
import { executeSql } from '../util/db.js'

// 根据文章ID获取评论列表 (默认显示15条)
export const selectCommentsByArticleId = function(articleId, page = 1, pageSize = 15){
    let pageInt = parseInt(page) || 1;
    let pageSizeInt = parseInt(pageSize) || 15;
    let offset = (pageInt - 1) * pageSizeInt;
    let sql = `select * from comments where articleId = ? and state = ? order by date desc, time desc limit ${offset}, ${pageSizeInt}`;
    return executeSql(sql, [parseInt(articleId), '已通过']);
}

// 获取评论总数
export const selectCommentsCount = function(articleId){
    if(articleId) {
        let sql = `select count(id) count from comments where articleId = ? and state = ?`;
        return executeSql(sql, [parseInt(articleId), '已通过']);
    } else {
        // 管理后台用：获取所有评论总数
        let sql = `select count(id) count from comments`;
        return executeSql(sql);
    }
}

// 添加评论
export const insertComment = function(author, content, articleId){
    let now = new Date();
    // "2025-08-13T15:30:45.123Z" => ["2025-08-13", "15:30:45.123Z"] => 2025-08-13
    let date = now.toISOString().split('T')[0]; 
    // "15:30:45 GMT+0800 (中国标准时间)" =>  ["15:30:45", "GMT+0800", "(中国标准时间)"] => "15:30:45"
    let time = now.toTimeString().split(' ')[0]; 
    let sql = `insert into comments (author, content, articleId, date, time, state) values (?, ?, ?, ?, ?, ?)`; // 状态需要设置已通过，这样根据文章ID获取评论列表，可以显示出来
    return executeSql(sql, [author, content, parseInt(articleId), date, time, '已通过']);
}

//------------------管理后台相关----------------------
// 获取所有评论 (分页)
export const selectAllComments = function(page = 1, pageSize = 6){
    let pageInt = parseInt(page) || 1;
    let pageSizeInt = parseInt(pageSize) || 6;
    let offset = (pageInt - 1) * pageSizeInt;
    let sql = `select c.*, a.title as articleTitle from comments c left join articles a on c.articleId = a.id order by c.date desc, c.time desc limit ${offset}, ${pageSizeInt}`;
    return executeSql(sql);
}

// 更新评论状态
export const updateCommentState = function(id, state){
    let sql = `update comments set state = ? where id = ?`;
    return executeSql(sql, [state, parseInt(id)]);
}

// 删除评论
export const deleteComment = function(id){
    let sql = `delete from comments where id = ?`;
    return executeSql(sql, [parseInt(id)]);
}

// 获取今日评论数量
export const selectTodayCommentsCount = function(today){
    let sql = `select count(id) count from comments where date = ?`;
    return executeSql(sql, [today]);
}
